const qs = require('qs')
const axios = require('axios')
const { minify } = require('html-minifier')

const writer = require('../utils/writer')
const { info, success } = require('../utils/output')
const { warrantParamsParser } = require('../utils/parser')
const { pageProcessor, warrantProcessor } = require('../utils/page')
const { staticPagePath, staticWarrantPath } = require('../utils/path')

const minifyOptions = {
  minifyJS: true,
  removeComments: true,
  collapseWhitespace: true,
  removeScriptTypeAttributes: true
}

module.exports = async (pageUrl, warrantUrl, id) => {
  // 解析提交申请的页面 并加工后写入本地文件
  info('尝试获取页面信息...')
  const params = { id }
  const { data } = await axios.get(pageUrl, { params })
  const warrantParams = warrantParamsParser(data)
  const page = pageProcessor(data)
  success('获取成功')
  info('写入文件...')
  await writer(staticPagePath, minify(page, minifyOptions))
  
  // 解析页面上是否存在可获取的临时凭证 若是则解析凭证页面 加工后写入文件
  if (page.includes('获取临时凭证') && warrantParams) {
    info('尝试获取临时凭证...')
    const params = qs.parse(warrantParams)
    const res = await axios.get(warrantUrl, { params })
    const { data } = res
    const page = warrantProcessor(data)
    success('获取成功')
    info('写入文件...')
    await writer(staticWarrantPath, minify(page, minifyOptions))
  }
}